# coding: utf-8
import random
import uiautomator2 as u2
import pytest,allure,json
from common.csv_data import write_csv_list
import time
from time import strftime
from time import gmtime
from common.logger import Logger
from common.operation_excle import operation_excle
from common.logger import Logger

# devices=['6d5b932e','emulator-5554']

#命令行传参addoption 在contetest.py添加命令行选项,命令行传入参数”—cmdopt“, 用例如果需要用到从命令行传入的参数，就调用cmdopt函数：
def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store", default="device_info", help=None)

#命令行传参addoption 在contetest.py添加命令行选项,命令行传入参数”—cmdopt“, 用例如果需要用到从命令行传入的参数，就调用cmdopt函数：
@pytest.fixture(scope='session')
def cmdopt(pytestconfig):
    # 两种写法

    #global parameter_data
    #parameter_data=eval(pytestconfig.getoption("--cmdopt"))
    parameter_data =eval(pytestconfig.getoption("--cmdopt"))

    return parameter_data
    # return pytestconfig.option.cmdopt


# @pytest.fixture(scope='session',autouse=True)
# def driver(cmdopt):
#     #cmdopt="d5b932e"
#     global driver
#
#     driver = u2.connect(cmdopt)
#     driver.implicitly_wait(120)
#     driver.app_start('com.tencent.mm', stop=True, wait=True)
#
#
#     yield driver
#     # yield drivers
#     driver.app_stop('com.tencent.mm')



@pytest.fixture(scope='session',autouse=True)
def drivers_devices(cmdopt):#={"devices_list":['0123456789ABCDEF'],"test_case_path":'./test_case','test_data_yaml':"group_data_1.yaml",'NO':"1"},
    #cmdopt="d5b932e"
    global drivers
    devices=cmdopt['devices_list']

    drivers=[]
    for dev in devices:
        d = u2.connect(dev)

        d.implicitly_wait(120)
        drivers.append(d)


    yield [drivers,devices,cmdopt]
    # yield drivers





@pytest.fixture(scope='function',autouse=True)
def dri_dev(drivers_devices):
    drivers,devices,device_info=drivers_devices

    mv_path_list=[]
    for d,dev in zip(drivers,devices):
        time.sleep(2)
        runtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        mv_path = './screen/%s_%s.mp4'%(runtime,dev)

        #安装录屏插件
        # pip3 install -U "uiautomator2[image]" -i https://pypi.doubanio.com/simple
        try:
            d.screenrecord(mv_path)
            mv_path_list.append(mv_path)
        except Exception as e:
            Logger.error('%s设备录屏出错！！（报错：%s）'%(dev,str(e)))
            mv_path = './config/example.png'
            mv_path_list.append(mv_path)

        d.app_start('com.tencent.mm', stop=True, wait=True)


    yield

    for d,dev,mv_path in zip(drivers,devices,mv_path_list):
        d.app_stop('com.tencent.mm')
        time.sleep(2)
        d.screenrecord.stop()
        with allure.step('录屏【%s】：'%dev):
            allure.attach.file(mv_path, name='录屏文件', attachment_type=allure.attachment_type.MP4)





@pytest.fixture(scope="session",autouse=True)
def dev_srt_naem(cmdopt):#将多个设备序列号，连为一个字符串
    devices = cmdopt['devices_list']
    dev_name_srt=''
    for i in devices:
        dev_name_srt="%s_%s"%(dev_name_srt,i)
    return dev_name_srt[1:]


@pytest.fixture(scope='session',autouse=True)
def total_calculation(dev_srt_naem):  #汇总每个模块的数据
    dic_data_total=[]
    starttime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(starttime))
    dic_data = {
        'module_tets': '项目测试总耗时',
        'dev_srt_naem':dev_srt_naem,
        'starttime': '',
        'endtime': '',
        'testtime': ''
    }
    dic_data.update({
        'starttime': formatTime
    })
    yield dic_data_total

    endtime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime))
    dic_data.update({
        'endtime': formatTime,
        'testtime': (strftime("%H:%M:%S", gmtime(endtime - starttime)))

    })
    dic_data_total.append(dic_data)


    #print(dic_data_total)
    header_data=''
    dic_data_list=[]#每个模块数据列表
    for dic_data in dic_data_total:
        header_data=list(dic_data.keys())
        dic_data_list.append(list(dic_data.values()))



    runtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
    #path: str, sheetStr, info, data
    #path_excle='./excle-report/%s_%s.xlsx'%(dev_srt_naem,runtime,)
    path_excle = './target/%s.xlsx' % (dev_srt_naem)
    header_data=['测试项','测试设备','开测时间','结束时间','测试耗时']
    operation_excle.write_to_excel(path_excle,'%s_项目耗时统计'%runtime,header_data,dic_data_list)#'%s_项目耗时统计'%runtime



    #path_csv='./excle-report/%s_%s.csv' % (dev_srt_naem, runtime,)
    path_csv='./target/%s.csv' % (dev_srt_naem)
    write_csv_list(path_csv,dic_data_list)
    time.sleep(1)
    with allure.step('项目耗时统计'):
        allure.attach.file(path_csv, name=path_csv,
                           attachment_type=allure.attachment_type.CSV)  # 测试步骤中添加一张图片或视频

    # with allure.step('项目耗时统计'):
    #     allure.attach(
    #         json.dumps(dic_data_list, ensure_ascii=False, indent=4),
    #         "附件内容",
    #         allure.attachment_type.JSON,
    #     )
    #


@pytest.fixture(scope='module',autouse=True)
def calculation(total_calculation,dev_srt_naem):#获取每个模块的数据

    starttime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(starttime))
    dic_data={
    'module_tets': '',
    'dev_srt_naem': dev_srt_naem,
	'starttime': '',
	'endtime': '',
	'testtime': ''
}
    dic_data.update({
        'starttime':formatTime
    })
    yield dic_data

    endtime = int(time.time())
    formatTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime))
    dic_data.update({
        'endtime':formatTime,
        'testtime':(strftime("%H:%M:%S", gmtime(endtime - starttime)))

    })
    total_calculation.append(dic_data)


def pytest_itemcollected(item):#加随机数区分多进程用例

    # item._nodeid = '%s_%s_%s' %(dev[0],dev[1],item . _nodeid)
    #runtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
    item._nodeid = str(random.randint(1, 1000)) + '_' + item._nodeid
    #item._nodeid = str(runtime) + '_' + item._nodeid

